package com.xm.libretranslate.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Service
public class TranslationService {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${libretranslate.url}")
    private String libreTranslateUrl;

    public String translateText(String text, String sourceLang, String targetLang) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("q", text);
        requestBody.put("source", sourceLang);
        requestBody.put("target", targetLang);
        requestBody.put("format", text);
        requestBody.put("alternatives", 3);
        requestBody.put("api_key", "");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        Map response = restTemplate.postForObject(libreTranslateUrl, requestEntity, Map.class);
        if (response!= null && response.containsKey("translatedText")) {
            return (String) response.get("translatedText");
        }
        return null;
    }
}